module(..., package.seeall)
local _large_char = string.char(1)
function CmpSub(id1,id2)
	local i1,n1 = string.gsub(id1,'/',_large_char)
	local i2,n2 = string.gsub(id2,'/',_large_char)
	if n1 == n2 then return i1 < i2 end
	return n1 < n2
end

function IsRoot(root,chi)
	if root==chi then return true end
	local len=#root
	if #chi < len then return false end
	if string.sub(chi,1,len)~= root or string.byte(chi,len+1) ~= 47 then
		return false
	end
	return true
end

function IsParent(parent,chi)
	local len=#parent
	if #chi <= len then return false end
	if len==0 then
		if string.find(chi,'/') then return false else return true end
	end
	if string.sub(chi,1,len)~= parent or string.byte(chi,len+1) ~= 47 or string.find(chi,'/',len+2) then
		return false
	end
	return true
end
function GetParent(id)
	return string.match(id, "^(.+)/(.-)$")
end
function GetSegment(id)
	local seg={}
	for s in string.gmatch(id,'[^/]+') do
		table.insert(seg,s)
	end
	return seg
end
function MergeRoot(t)
	local tl={}
	for k,v in pairs(t) do
		tl[#tl+1]=k
	end
	table.sort(tl,CmpSub)
	return tl
end
function SortChildNodes(cs)
	local t={}
	for k,v in pairs(cs) do
		table.insert(t,k)
	end
	table.sort(t,function(a,b)
		local aik,bik=cs[a].__ik,cs[b].__ik
		if aik==bik then
			return a<b
		else
			return aik<bik
		end
	end)
	return t
end

function PreRemove(id,pre)
	if pre==string.sub(id,1,#pre) then
		return string.sub(id,#pre+1)
	end
end

function GetRelID(id,baseid,env)
	local _,pos=string.find(id,"^[%.]+")
	if pos then
		for c=pos,2 do
			baseid=string.match(baseid, "^(.+)/(.-)$")
		end
		id=baseid..id:sub(pos+1)
	end
	local newid=''
	for text, block in string.gmatch(id..'{}', "([^{]-)(%b{})") do
		newid=newid..text
		if #block>2 then
			newid=newid..tostring(env[block:sub(2,-2)])
		end
	end
	return newid
end
